<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>医生管理 - 智慧小区管理系统</title>
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css">
    <script src="../lib/jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style>
        body { padding: 24px; background: #f5f7fa; }
        .doctor-toolbar { margin-bottom: 16px; }
        .layui-table th, .layui-table td { text-align: center; }
        .service-type-badge { padding: 4px 8px; border-radius: 4px; font-size: 12px; color: white; }
        .service-therapy { background-color: #1E9FFF; }
        .service-consultation { background-color: #5FB878; }
    </style>
</head>
<body>
<div class="layui-card">
    <div class="layui-card-header" style="font-size:1.2em;font-weight:bold;display:flex;justify-content:space-between;align-items:center;">
        <span>医生管理</span>
        <div>
            <button class="layui-btn layui-btn-sm layui-btn-normal" id="addDoctorBtn"><i class="layui-icon layui-icon-add-1"></i> 新增医生</button>
            <button class="layui-btn layui-btn-sm layui-btn-warm" id="serviceConfigBtn"><i class="layui-icon layui-icon-set"></i> 医疗服务配置</button>
        </div>
    </div>
    <div class="layui-card-body">
        <!-- 搜索表单 -->
        <form class="layui-form doctor-toolbar" id="searchForm">
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 80px;">服务类型</label>
                <div class="layui-input-inline" style="width: 120px;">
                    <select name="serviceType" id="serviceTypeSelect">
                        <option value="">全部类型</option>
                    </select>
                </div>
            </div>
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="search">
                <i class="layui-icon layui-icon-search"></i> 查询
            </button>
            <button class="layui-btn layui-btn-primary" type="reset">
                <i class="layui-icon layui-icon-refresh"></i> 重置
            </button>
        </form>
        <!-- 数据表格 -->
        <table class="layui-table" id="doctorTable" lay-filter="doctorTableFilter"></table>
        <!-- 操作栏模板 -->
        <script type="text/html" id="tableBar">
            <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="detail">详情</a>
            <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
        </script>
    </div>
</div>
<script src="../lib/layui-v2.6.3/layui.js"></script>
<script>
layui.use(['table', 'form', 'layer', 'jquery'], function () {
    const table = layui.table;
    const form = layui.form;
    const layer = layui.layer;
    const $ = layui.jquery;
    let serviceTypeMap = {};
    let serviceTypeList = [];
    let doctorData = [];
    // 全局设置ajax请求头
    $.ajaxSetup({
        beforeSend: function(xhr) {
            const data = JSON.parse(localStorage.getItem('user'));
            //输出token
            console.log(data.token);
            if (data.token) {
                xhr.setRequestHeader('Authorization', 'Bearer ' + data.token);
            }
        }
    });
    // 动态加载服务类型
    function loadServiceTypes(callback) {
        $.get('/medical/services', function(res) {
            var $select = $('#serviceTypeSelect');
            $select.empty();
            $select.append('<option value="">全部类型</option>');
            if (res.code === 0 && Array.isArray(res.data)) {
                serviceTypeList = res.data;
                res.data.forEach(function(item) {
                    $select.append('<option value="'+item.serviceType+'">'+item.serviceName+'</option>');
                    serviceTypeMap[item.serviceType] = item.serviceName;
                });
            }
            form.render('select');
            if (callback) callback();
        });
    }
    // 加载医生数据并合并服务配置信息
    function loadDoctors(filter) {
        $.get('/medical/doctors', function(res) {
            if(res.code === 0 && Array.isArray(res.data)) {
                // 合并服务配置信息
                doctorData = res.data.map(function(doc) {
                    var st = serviceTypeList.find(function(s) { return s.serviceType === doc.serviceType; });
                    return Object.assign({}, doc, {
                        location: st ? st.location : '',
                        duration: st ? st.duration : '',
                        price: st ? st.price : ''
                    });
                });
                renderDoctorTable(filter);
            } else {
                table.render({elem:'#doctorTable',data:[],cols:[[]]});
            }
        });
    }
    // 渲染表格
    function renderDoctorTable(filter) {
        let data = doctorData;
        if(filter && filter.serviceType) {
            data = data.filter(function(d){ return String(d.serviceType) === String(filter.serviceType); });
        }
        table.render({
            elem: '#doctorTable',
            id: 'doctorTable',
            data: data,
            page: true,
            limit: 10,
            cols: [[
                { field: 'doctorId', title: '医生ID', minWidth: 80, align: 'center' },
                { field: 'doctorName', title: '姓名', minWidth: 100, align: 'center' },
                { field: 'phone', title: '联系电话', minWidth: 120, align: 'center' },
                { field: 'serviceType', title: '服务类型', minWidth: 120, align: 'center', templet: function(d) {
                    return serviceTypeMap[d.serviceType] || '<span style="color:#bbb;">未知类型</span>';
                } },
                { field: 'location', title: '地点', minWidth: 120, align: 'center' },
                { field: 'duration', title: '时长(分钟)', minWidth: 80, align: 'center' },
                { field: 'price', title: '价格', minWidth: 80, align: 'center', templet: function(d){ return d.price ? '¥'+parseFloat(d.price).toFixed(2) : ''; } },
                { title: '操作', minWidth: 90, align: 'center', toolbar: '#tableBar' }
            ]]
        });
    }
    // 医生表单弹窗HTML
    var doctorFormHtml = `
        <form class="layui-form" id="doctorForm" lay-filter="doctorForm" style="padding:24px 18px 0 18px;max-width:480px;">
            <input type="hidden" name="doctorId">
            <div class="layui-form-item">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="doctorName" required lay-verify="required" placeholder="请输入姓名" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">服务类型</label>
                <div class="layui-input-block">
                    <select name="serviceType" required lay-verify="required">
                        <option value="">请选择服务类型</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">联系电话</label>
                <div class="layui-input-block">
                    <input type="text" name="phone" required lay-verify="required" placeholder="请输入联系电话" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">工作日</label>
                <div class="layui-input-block">
                    <input type="text" name="workDays" placeholder="如1,2,3,4,5" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">时间段</label>
                <div class="layui-input-block">
                    <input type="text" name="workTimeSlots" placeholder="如上午9:00-10:00,下午14:00-15:00" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">头像</label>
                <div class="layui-input-block">
                    <input type="hidden" name="avatarUrl" id="avatarUrlInput">
                    <button type="button" class="layui-btn" id="uploadAvatarBtn"><i class="layui-icon">&#xe67c;</i>上传头像</button>
                    <div id="avatarPreview" style="margin-top:8px;"></div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">服务简介</label>
                <div class="layui-input-block">
                    <input type="text" name="profile" placeholder="医生简介，可选" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block" style="text-align:right;">
                    <button class="layui-btn layui-btn-normal" lay-submit lay-filter="submitDoctor">提交</button>
                </div>
            </div>
        </form>
    `;
    // 头像上传控件初始化
    function initAvatarUpload(layero, oldUrl) {
        var $preview = layero.find('#avatarPreview');
        var $input = layero.find('input[name="avatarUrl"]');
        $preview.html('');
        if (oldUrl) {
            $preview.html('<img src="'+oldUrl+'" style="width:80px;height:80px;border-radius:50%;object-fit:cover;">');
        }
        layero.find('#uploadAvatarBtn').off('click').on('click', function(){
            var $file = $('<input type="file" accept="image/*" style="display:none;">');
            $('body').append($file);
            $file.on('change', function(){
                var file = this.files[0];
                if (!file) return;
                var formData = new FormData();
                formData.append('file', file);
                $.ajax({
                    url: '/oss/upload',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        if(res.code === 0) {
                            $input.val(res.data);
                            $preview.html('<img src="'+res.data+'" style="width:80px;height:80px;border-radius:50%;object-fit:cover;">');
                            layer.msg('上传成功', {icon: 1});
                        } else {
                            layer.msg(res.message || '上传失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('上传失败', {icon: 2});
                    },
                    complete: function() {
                        $file.remove();
                    }
                });
            });
            $file.click();
        });
    }
    // 初始化
    loadServiceTypes(function() {
        loadDoctors({});
    });
    // 查询表单提交
    form.on('submit(search)', function (data) {
        loadDoctors(data.field);
        return false;
    });
    // 重置按钮
    $(document).on('click', '.layui-btn-primary[type="reset"]', function () {
        $('#searchForm')[0].reset();
        form.render();
        loadDoctors({});
        return false;
    });
    // 新增医生按钮
    $(document).on('click', '#addDoctorBtn', function() {
        layer.open({
            type: 1,
            title: '新增医生',
            area: ['500px','auto'],
            shadeClose: true,
            content: doctorFormHtml,
            success: function(layero, idx) {
                // 渲染服务类型下拉
                var $select = layero.find('select[name="serviceType"]');
                $select.empty();
                $select.append('<option value="">请选择服务类型</option>');
                serviceTypeList.forEach(function(st){
                    $select.append('<option value="'+st.serviceType+'">'+st.serviceName+'</option>');
                });
                form.render('select');
                // 初始化头像上传
                initAvatarUpload(layero, '');
            }
        });
    });
    // 编辑医生
    table.on('tool(doctorTableFilter)', function(obj){
        if(obj.event === 'edit') {
            window._lastEditAvatarUrl = obj.data.avatarUrl || '';
            var d = obj.data;
            layer.open({
                type: 1,
                title: '编辑医生',
                area: ['500px','auto'],
                shadeClose: true,
                content: doctorFormHtml,
                success: function(layero, idx) {
                    // 渲染服务类型下拉
                    var $select = layero.find('select[name="serviceType"]');
                    $select.empty();
                    $select.append('<option value="">请选择服务类型</option>');
                    serviceTypeList.forEach(function(st){
                        $select.append('<option value="'+st.serviceType+'">'+st.serviceName+'</option>');
                    });
                    form.render('select');
                    setTimeout(function(){
                        form.val('doctorForm', d);
                        // 初始化头像上传，传入旧头像
                        initAvatarUpload(layero, d.avatarUrl);
                    }, 0);
                }
            });
        } else if(obj.event === 'delete') {
            var avatarUrl = obj.data.avatarUrl;
            layer.confirm('确定要删除该医生吗？', function(index){
                // 先删医生，再删头像（如有）
                $.ajax({
                    url: '/medical/doctors/delete',
                    type: 'POST',
                    data: { doctorId: Number(obj.data.doctorId) },
                    success: function(res) {
                        if(res.code === 0) {
                            if(avatarUrl) {
                                $.ajax({
                                    url: '/oss/delete',
                                    type: 'DELETE',
                                    data: { fileUrl: avatarUrl },
                                    success: function(r) {},
                                    error: function() {}
                                });
                            }
                            layer.msg('删除成功', {icon: 1});
                            loadDoctors({});
                        } else {
                            layer.msg(res.message || '删除失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('网络错误，删除失败', {icon: 2});
                    },
                    complete: function() {
                        layer.close(index);
                    }
                });
            });
        }else if(obj.event === 'detail') {
            var d = obj.data;
            var workDays = d.workDays ? d.workDays.split(',').map(function(n){return '一二三四五六日'[parseInt(n)-1];}).join('、') : '';
            var timeSlots = d.workTimeSlots ? d.workTimeSlots.split(',').join('、') : '';
            var html = `
                <div style="display:flex;gap:48px;min-width:520px;max-width:680px;padding:32px 28px 28px 28px;">
                    <div style="flex:0 0 140px;text-align:center;">
                        <img src="${d.avatarUrl?d.avatarUrl:'../images/default_picture.png'}" style="width:112px;height:112px;border-radius:50%;border:2px solid #e6e6e6;object-fit:cover;box-shadow:0 2px 8px #eee;">
                        <div style="margin-top:20px;font-size:1.18em;font-weight:bold;">${d.doctorName}</div>
                        <div style="color:#888;font-size:1em;margin-top:8px;">${d.phone||''}</div>
                    </div>
                    <div style="flex:1;min-width:260px;">
                        <div style="margin-bottom:20px;">
                            <span class="service-type-badge ${(d.serviceType===1?'service-therapy':'service-consultation')}" style="font-size:1.15em;vertical-align:middle;">${serviceTypeMap[d.serviceType]||''}</span>
                            <span style="color:#e74c3c;font-size:1.28em;font-weight:bold;margin-left:22px;vertical-align:middle;">${d.price ? '¥'+parseFloat(d.price).toFixed(2) : ''}</span>
                        </div>
                        <div style="margin-bottom:18px;color:#666;line-height:1.9;"><b>服务描述：</b>${d.serviceDescription||'无'}</div>
                        <div style="margin-bottom:18px;color:#666;line-height:1.9;"><b>医生简介：</b>${d.profile||'无'}</div>
                        <div style="display:flex;flex-wrap:wrap;gap:18px 38px;margin-top:18px;font-size:1.05em;line-height:2.1;">
                            <div><b>工作日：</b>${workDays}</div>
                            <div><b>时间段：</b>${timeSlots}</div>
                            <div><b>地点：</b>${d.location}</div>
                            <div><b>时长：</b>${d.duration} 分钟</div>
                        </div>
                    </div>
                </div>
            `;
            layer.open({
                type: 1,
                title: '医生详情',
                area: ['680px','auto'],
                shadeClose: true,
                content: html
            });
        }
    });
    // 提交表单（新增/编辑）
    form.on('submit(submitDoctor)', function(data) {
        var field = data.field;
        var isEdit = !!field.doctorId;
        var url = isEdit ? '/medical/doctors/update' : '/medical/doctors/add';
        // 编辑时如更换头像，需删除旧头像
        if(isEdit && window._lastEditAvatarUrl && window._lastEditAvatarUrl !== field.avatarUrl && window._lastEditAvatarUrl !== ''){
            $.ajax({
                url: '/oss/delete',
                type: 'DELETE',
                data: { fileUrl: window._lastEditAvatarUrl },
                success: function(r) {},
                error: function() {}
            });
        }
        $.ajax({
            url: url,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(field),
            success: function(res) {
                if(res.code === 0) {
                    layer.msg(isEdit ? '修改成功' : '添加成功', {icon: 1});
                    layer.closeAll();
                    loadDoctors({});
                } else {
                    layer.msg(res.message || (isEdit ? '修改失败' : '添加失败'), {icon: 2});
                }
            },
            error: function() {
                layer.msg('网络错误，操作失败', {icon: 2});
            }
        });
        return false;
    });
    // 医疗服务配置弹窗HTML
    var serviceConfigHtml = `
        <div style="padding:18px 10px 0 10px;">
            <button class="layui-btn layui-btn-sm layui-btn-normal" id="addServiceConfigBtn"><i class="layui-icon layui-icon-add-1"></i> 新增服务配置</button>
            <table class="layui-table" id="serviceConfigTable" lay-filter="serviceConfigTable"></table>
        </div>
    `;
    // 服务配置表单
    var serviceConfigFormHtml = `
        <form class="layui-form" id="serviceConfigForm" lay-filter="serviceConfigForm" style="padding:18px 10px 0 10px;max-width:480px;">
            <div class="layui-form-item">
                <label class="layui-form-label">类型ID</label>
                <div class="layui-input-block">
                    <input type="number" name="serviceType" required lay-verify="required" placeholder="唯一ID" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">服务名称</label>
                <div class="layui-input-block">
                    <input type="text" name="serviceName" required lay-verify="required" placeholder="服务名称" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">描述</label>
                <div class="layui-input-block">
                    <input type="text" name="serviceDescription" placeholder="描述" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">时长(分钟)</label>
                <div class="layui-input-block">
                    <input type="number" name="duration" placeholder="时长" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">价格</label>
                <div class="layui-input-block">
                    <input type="number" name="price" placeholder="价格" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">地点</label>
                <div class="layui-input-block">
                    <input type="text" name="location" placeholder="地点" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block" style="text-align:right;">
                    <button class="layui-btn layui-btn-normal" lay-submit lay-filter="submitServiceConfig">提交</button>
                </div>
            </div>
        </form>
    `;
    // 医疗服务配置弹窗
    $(document).on('click', '#serviceConfigBtn', function() {
        layer.open({
            type: 1,
            title: '医疗服务配置',
            area: ['800px','600px'],
            shadeClose: true,
            content: serviceConfigHtml,
            success: function(layero, idx) {
                loadServiceConfigTable(layero);
            }
        });
    });
    // 加载服务配置表格
    function loadServiceConfigTable(layero) {
        $.get('/medical/services', function(res) {
            var data = res.data || [];
            table.render({
                elem: layero.find('#serviceConfigTable')[0],
                id: 'serviceConfigTable',
                data: data,
                page: false,
                cols: [[
                    { field: 'serviceType', title: '类型ID', minWidth: 80, align: 'center' },
                    { field: 'serviceName', title: '服务名称', minWidth: 120, align: 'center' },
                    { field: 'serviceDescription', title: '描述', minWidth: 180, align: 'center' },
                    { field: 'duration', title: '时长(分钟)', minWidth: 80, align: 'center' },
                    { field: 'price', title: '价格', minWidth: 80, align: 'center', templet: function(d){ return d.price ? '¥'+parseFloat(d.price).toFixed(2) : ''; } },
                    { field: 'location', title: '地点', minWidth: 120, align: 'center' },
                    { title: '操作', minWidth: 120, align: 'center', toolbar: '#serviceConfigBar' }
                ]]
            });
        });
    }
    // 服务配置操作栏模板
    $("body").append(`
    <script type="text/html" id="serviceConfigBar">
        <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
    <\/script>
    `);
    // 新增服务配置
    $(document).on('click', '#addServiceConfigBtn', function() {
        window._serviceConfigEdit = false;
        layer.open({
            type: 1,
            title: '新增服务配置',
            area: ['500px','auto'],
            shadeClose: true,
            content: serviceConfigFormHtml,
            success: function(layero, idx) {
                form.render();
            }
        });
    });
    // 编辑/删除服务配置
    table.on('tool(serviceConfigTable)', function(obj){
        if(obj.event === 'edit') {
            window._serviceConfigEdit = true;
            var d = obj.data;
            layer.open({
                type: 1,
                title: '编辑服务配置',
                area: ['500px','auto'],
                shadeClose: true,
                content: serviceConfigFormHtml,
                success: function(layero, idx) {
                    form.val('serviceConfigForm', d);
                    form.render();
                }
            });
        } else if(obj.event === 'delete') {
            layer.confirm('确定要删除该服务配置吗？', function(index){
                $.ajax({
                    url: '/medical/services/delete',
                    type: 'POST',
                    data: { serviceType: obj.data.serviceType },
                    success: function(res) {
                        if(res.code === 0) {
                            layer.msg('删除成功', {icon: 1});
                            loadServiceConfigTable($('body'));
                        } else {
                            layer.msg(res.message || '删除失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('网络错误，删除失败', {icon: 2});
                    },
                    complete: function() {
                        layer.close(index);
                    }
                });
            });
        }
    });
    // 提交服务配置表单
    form.on('submit(submitServiceConfig)', function(data) {
        var field = data.field;
        var isEdit = window._serviceConfigEdit;
        var url = isEdit ? '/medical/services/update' : '/medical/services/add';
        $.ajax({
            url: url,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(field),
            success: function(res) {
                if(res.code === 0) {
                    layer.msg(isEdit ? '修改成功' : '添加成功', {icon: 1});
                    layer.closeAll();
                    loadServiceConfigTable($('body'));
                } else {
                    layer.msg(res.message || (isEdit ? '修改失败' : '添加失败'), {icon: 2});
                }
            },
            error: function() {
                layer.msg('网络错误，操作失败', {icon: 2});
            }
        });
        return false;
    });
});
</script>
</body>
</html> 